package chapters.appenders.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;

/**
 * Created by YLC on 2017/11/8 0008.
 */
public class SocketServerTest {
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            ServerSocket server = serverSocketChannel.socket();
            SocketAddress sa = new InetSocketAddress("localhost", 4321);
            server.bind(sa);
            while (true){
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                SocketChannel sc = serverSocketChannel.accept();
                sc.read(buffer);
                buffer.flip();
                int limit = buffer.limit();//在flip()后取limit的值
                byte[] bs = new byte[limit];
                buffer.get(bs, 0, limit);
                System.out.println(bs);
                String request = new String(bs);
                buffer.clear();

                System.out.println("收到socket消息："+ request+", Time:"+(new Date()));
                Thread.sleep(10000L);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
